<template>
  <div class="distributor-table-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="spinner"></div>
      <p>加载分销商数据中...</p>
    </div>

    <!-- 数据为空状态 -->
    <div v-else-if="paginatedDistributors.length === 0" class="empty-state">
      <i class="fas fa-users-slash"></i>
      <p>{{ filteredDistributors.length === 0 ? '未找到符合条件的分销商' : '暂无分销商数据' }}</p>
      <button v-if="hasActiveFilters" class="reset-btn" @click="resetFilters">重置筛选条件</button>
    </div>

    <!-- 数据表格 -->
    <div v-else class="table-wrapper">
      <table class="distributor-table">
        <thead>
          <tr>
            <th @click="sortBy('name')" class="sortable">
              分销商名称
              <i v-if="sortField === 'name'" :class="['fas', sortDirection === 'asc' ? 'fa-sort-up' : 'fa-sort-down']">
              </i>
              <i v-else class="fas fa-sort"></i>
            </th>
            <th @click="sortBy('commissionRate')" class="sortable">
              佣金比例
              <i v-if="sortField === 'commissionRate'"
                :class="['fas', sortDirection === 'asc' ? 'fa-sort-up' : 'fa-sort-down']">
              </i>
              <i v-else class="fas fa-sort"></i>
            </th>
            <th @click="sortBy('totalSales')" class="sortable">
              累计销售额
              <i v-if="sortField === 'totalSales'"
                :class="['fas', sortDirection === 'asc' ? 'fa-sort-up' : 'fa-sort-down']">
              </i>
              <i v-else class="fas fa-sort"></i>
            </th>
            <th @click="sortBy('totalOrders')" class="sortable">
              累计订单数
              <i v-if="sortField === 'totalOrders'"
                :class="['fas', sortDirection === 'asc' ? 'fa-sort-up' : 'fa-sort-down']">
              </i>
              <i v-else class="fas fa-sort"></i>
            </th>
            <th @click="sortBy('totalCommission')" class="sortable">
              累计佣金
              <i v-if="sortField === 'totalCommission'"
                :class="['fas', sortDirection === 'asc' ? 'fa-sort-up' : 'fa-sort-down']">
              </i>
              <i v-else class="fas fa-sort"></i>
            </th>
            <th @click="sortBy('joinDate')" class="sortable">
              加入日期
              <i v-if="sortField === 'joinDate'"
                :class="['fas', sortDirection === 'asc' ? 'fa-sort-up' : 'fa-sort-down']">
              </i>
              <i v-else class="fas fa-sort"></i>
            </th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="distributor in paginatedDistributors" :key="distributor.id"
            :class="{ 'inactive': distributor.status === 'inactive' }">
            <td class="distributor-name">
              <div class="avatar-name">
                <div class="avatar">
                  <img :src="distributor.avatar" :alt="distributor.name">
                  <span class="status-dot" :class="statusClass(distributor.status)"></span>
                </div>
                <div class="name-info">
                  <span class="name">{{ distributor.name }}</span>
                  <span class="id">ID: {{ distributor.id }}</span>
                </div>
              </div>
            </td>
            <td>{{ distributor.commissionRate }}%</td>
            <td>¥{{ formatNumber(distributor.totalSales) }}</td>
            <td>{{ distributor.totalOrders }}</td>
            <td>¥{{ formatNumber(distributor.totalCommission) }}</td>
            <td>{{ distributor.joinDate }}</td>
            <td class="action-cell">
              <button class="action-btn view-btn" @click="viewDistributor(distributor)">
                <i class="fas fa-eye"></i> 查看
              </button>
              <button class="action-btn edit-btn" @click="editDistributor(distributor)">
                <i class="fas fa-edit"></i> 编辑
              </button>
              <button class="action-btn" :class="distributor.status === 'active' ? 'disable-btn' : 'enable-btn'"
                @click="toggleStatus(distributor)">
                <i class="fas" :class="distributor.status === 'active' ? 'fa-ban' : 'fa-check'"></i>
                {{ distributor.status === 'active' ? '禁用' : '启用' }}
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-container" v-if="filteredDistributors.length > 0">
      <div class="page-size">
        <span>每页显示：</span>
        <select v-model="pageSize" @change="handlePageSizeChange">
          <option :value="10">10条</option>
          <option :value="20">20条</option>
          <option :value="50">50条</option>
        </select>
      </div>
      <div class="pagination-controls">
        <button class="page-btn" :disabled="currentPage === 1" @click="changePage(1)">
          <i class="fas fa-angle-double-left"></i>
        </button>
        <button class="page-btn" :disabled="currentPage === 1" @click="changePage(currentPage - 1)">
          <i class="fas fa-angle-left"></i>
        </button>

        <div class="page-numbers">
          <button v-for="page in displayedPages" :key="page" class="page-number"
            :class="{ active: currentPage === page }" @click="changePage(page)">
            {{ page }}
          </button>
        </div>

        <button class="page-btn" :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">
          <i class="fas fa-angle-right"></i>
        </button>
        <button class="page-btn" :disabled="currentPage === totalPages" @click="changePage(totalPages)">
          <i class="fas fa-angle-double-right"></i>
        </button>
      </div>
      <div class="pagination-info">
        <span>共 {{ filteredDistributors.length }} 条数据</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { generateDistributorsData } from '@/utils/agentMock';

interface Distributor {
  id: string;
  name: string;
  avatar: string;
  commissionRate: number;
  totalSales: number;
  totalOrders: number;
  totalCommission: number;
  joinDate: string;
  status: 'active' | 'inactive' | 'pending';
}

// Props
interface Props {
  searchQuery?: string;
  statusFilter?: string;
  levelFilter?: string;
}

const props = withDefaults(defineProps<Props>(), {
  searchQuery: '',
  statusFilter: '',
  levelFilter: ''
});

// Emits
const emit = defineEmits<{
  (e: 'view', distributor: Distributor): void;
  (e: 'edit', distributor: Distributor): void;
  (e: 'toggle-status', distributor: Distributor): void;
  (e: 'page-change', page: number): void;
}>();

// 状态变量
const loading = ref(true);
const distributors = ref<Distributor[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const sortField = ref('joinDate');
const sortDirection = ref<'asc' | 'desc'>('desc');

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    // 在实际项目中，这里会调用API获取数据
    distributors.value = generateDistributorsData(50);
  } catch (error) {
    console.error('获取分销商数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 格式化数字
const formatNumber = (num: number): string => {
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

// 状态样式类
const statusClass = (status: string): string => {
  switch (status) {
    case 'active': return 'status-active';
    case 'pending': return 'status-pending';
    case 'inactive': return 'status-inactive';
    default: return '';
  }
};

// 筛选后的分销商数据
const filteredDistributors = computed(() => {
  let result = [...distributors.value];

  // 搜索功能
  if (props.searchQuery) {
    const query = props.searchQuery.toLowerCase();
    result = result.filter(item =>
      item.name.toLowerCase().includes(query) ||
      item.id.toLowerCase().includes(query)
    );
  }

  // 状态筛选
  if (props.statusFilter) {
    result = result.filter(item => item.status === props.statusFilter);
  }

  // 排序功能
  result.sort((a, b) => {
    const aValue = a[sortField.value as keyof Distributor];
    const bValue = b[sortField.value as keyof Distributor];

    // 处理不同类型的字段
    if (typeof aValue === 'number' && typeof bValue === 'number') {
      return sortDirection.value === 'asc' ? aValue - bValue : bValue - aValue;
    } else {
      const aStr = String(aValue);
      const bStr = String(bValue);
      return sortDirection.value === 'asc'
        ? aStr.localeCompare(bStr, 'zh-CN')
        : bStr.localeCompare(aStr, 'zh-CN');
    }
  });

  return result;
});

// 分页后的数据
const paginatedDistributors = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return filteredDistributors.value.slice(startIndex, endIndex);
});

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredDistributors.value.length / pageSize.value) || 1;
});

// 显示的页码
const displayedPages = computed(() => {
  const pages = [];
  const maxVisiblePages = 5;

  // 总页数小于最大可见页码
  if (totalPages.value <= maxVisiblePages) {
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i);
    }
  } else {
    // 总页数大于最大可见页码
    let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2));
    let endPage = startPage + maxVisiblePages - 1;

    if (endPage > totalPages.value) {
      endPage = totalPages.value;
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }
  }

  return pages;
});

// 是否有活跃的筛选条件
const hasActiveFilters = computed(() => {
  return !!props.searchQuery || !!props.statusFilter || !!props.levelFilter;
});

// 分页变化
const changePage = (page: number) => {
  currentPage.value = page;
  emit('page-change', page);
};

// 每页显示数量变化
const handlePageSizeChange = () => {
  currentPage.value = 1; // 重置到第一页
};

// 排序处理
const sortBy = (field: string) => {
  if (sortField.value === field) {
    // 切换排序方向
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc';
  } else {
    // 设置新的排序字段，默认降序
    sortField.value = field;
    sortDirection.value = 'desc';
  }
  currentPage.value = 1; // 重置到第一页
};

// 操作方法
const viewDistributor = (distributor: Distributor) => {
  emit('view', distributor);
};

const editDistributor = (distributor: Distributor) => {
  emit('edit', distributor);
};

const toggleStatus = (distributor: Distributor) => {
  emit('toggle-status', distributor);
};

// 重置筛选条件
const resetFilters = () => {
  // 通知父组件重置筛选
  emit('page-change', 1);
};

// 监听筛选条件变化
watch([() => props.searchQuery, () => props.statusFilter, () => props.levelFilter], () => {
  currentPage.value = 1; // 重置到第一页
});

// 生命周期钩子
onMounted(() => {
  fetchData();
});
</script>

<style lang="scss" scoped>
.distributor-table-container {
  margin-bottom: 24px;
}

// 加载状态
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;

  .spinner {
    display: inline-block;
    width: 40px;
    height: 40px;
    border: 3px solid rgba(74, 108, 247, 0.2);
    border-radius: 50%;
    border-top-color: #4a6cf7;
    animation: spin 1s linear infinite;
    margin-bottom: 16px;
  }

  p {
    font-size: 16px;
    color: #6c757d;
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;

  i {
    font-size: 48px;
    color: #e1e5eb;
    margin-bottom: 16px;
  }

  p {
    font-size: 16px;
    color: #6c757d;
    margin-bottom: 16px;
  }

  .reset-btn {
    padding: 8px 16px;
    background-color: #f8f9fa;
    border: 1px solid #e1e5eb;
    border-radius: 4px;
    color: #4a6cf7;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: #e9ecef;
    }
  }
}

// 表格样式
.table-wrapper {
  overflow-x: auto;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.distributor-table {
  width: 100%;
  border-collapse: collapse;

  thead {
    background-color: #f8f9fa;

    th {
      padding: 16px;
      text-align: left;
      font-weight: 600;
      color: #495057;
      border-bottom: 2px solid #e9ecef;
      white-space: nowrap;

      &.sortable {
        cursor: pointer;
        user-select: none;
        transition: background-color 0.3s;

        &:hover {
          background-color: #e9ecef;
        }

        i {
          margin-left: 4px;
          font-size: 12px;
          color: #adb5bd;
        }
      }
    }
  }

  tbody {
    tr {
      transition: background-color 0.3s;

      &:hover {
        background-color: #f8f9fa;
      }

      &:not(:last-child) {
        border-bottom: 1px solid #e9ecef;
      }

      &.inactive {
        background-color: #f8f9fa;
        opacity: 0.7;
      }

      td {
        padding: 16px;
        color: #212529;

        &.distributor-name {
          min-width: 220px;
        }
      }
    }
  }

  .avatar-name {
    display: flex;
    align-items: center;

    .avatar {
      position: relative;
      margin-right: 12px;

      img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        object-fit: cover;
        border: 1px solid #e9ecef;
      }

      .status-dot {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        border: 2px solid #fff;

        &.status-active {
          background-color: #28a745;
        }

        &.status-pending {
          background-color: #ffc107;
        }

        &.status-inactive {
          background-color: #dc3545;
        }
      }
    }

    .name-info {
      display: flex;
      flex-direction: column;

      .name {
        font-weight: 500;
        color: #212529;
      }

      .id {
        font-size: 12px;
        color: #6c757d;
        margin-top: 2px;
      }
    }
  }

  .action-cell {
    white-space: nowrap;

    .action-btn {
      padding: 6px 12px;
      border: none;
      border-radius: 4px;
      font-size: 13px;
      cursor: pointer;
      transition: all 0.3s;
      margin-right: 8px;

      &:last-child {
        margin-right: 0;
      }

      i {
        margin-right: 4px;
      }

      &.view-btn {
        background-color: #e9ecef;
        color: #495057;

        &:hover {
          background-color: #dee2e6;
        }
      }

      &.edit-btn {
        background-color: #e3f2fd;
        color: #0d6efd;

        &:hover {
          background-color: #cfe2ff;
        }
      }

      &.disable-btn {
        background-color: #f8d7da;
        color: #dc3545;

        &:hover {
          background-color: #f5c2c7;
        }
      }

      &.enable-btn {
        background-color: #d1e7dd;
        color: #198754;

        &:hover {
          background-color: #badbcc;
        }
      }
    }
  }
}

// 分页控件
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 24px;
  flex-wrap: wrap;
  gap: 16px;

  .page-size {
    display: flex;
    align-items: center;

    span {
      margin-right: 8px;
      color: #6c757d;
    }

    select {
      padding: 6px 12px;
      border: 1px solid #e1e5eb;
      border-radius: 4px;
      background-color: white;
      color: #495057;
      cursor: pointer;

      &:focus {
        outline: none;
        border-color: #4a6cf7;
      }
    }
  }

  .pagination-controls {
    display: flex;
    align-items: center;

    .page-btn {
      width: 36px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #e1e5eb;
      background-color: white;
      color: #495057;
      cursor: pointer;
      transition: all 0.3s;

      &:first-child {
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
      }

      &:last-child {
        border-top-right-radius: 4px;
        border-bottom-right-radius: 4px;
      }

      &:not(:first-child) {
        border-left: none;
      }

      &:hover:not(:disabled) {
        background-color: #f8f9fa;
      }

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }

    .page-numbers {
      display: flex;

      .page-number {
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #e1e5eb;
        background-color: white;
        color: #495057;
        cursor: pointer;
        transition: all 0.3s;
        border-left: none;

        &:hover:not(.active) {
          background-color: #f8f9fa;
        }

        &.active {
          background-color: #4a6cf7;
          color: white;
          border-color: #4a6cf7;
        }
      }
    }
  }

  .pagination-info {
    color: #6c757d;
    font-size: 14px;
  }
}

// 响应式调整
@media (max-width: 768px) {
  .distributor-table {

    thead th,
    tbody td {
      padding: 12px 8px;
      font-size: 14px;

      &:not(.distributor-name):not(.action-cell) {
        // 非关键列在小屏幕上可以隐藏
        display: none;
      }
    }

    .avatar-name {
      .avatar img {
        width: 32px;
        height: 32px;
      }
    }

    .action-cell {
      .action-btn {
        padding: 4px 8px;
        font-size: 12px;

        &:not(.view-btn) {
          span {
            display: none; // 只显示图标
          }
        }
      }
    }
  }

  .pagination-container {
    flex-direction: column;
    align-items: flex-start;

    .pagination-controls {
      width: 100%;
      justify-content: center;
      order: 1;
    }

    .page-size,
    .pagination-info {
      width: 100%;
      justify-content: space-between;
      order: 2;
    }
  }
}
</style>
